﻿using System;
using System.Web;
using System.Web.Mvc;
using Web.DataAccess;
using Web.Extensions;
using Web.Model;
using NHibernate;
using System.Drawing;
using Web.Security;
using Web.HelperClasses;

namespace Web.Controllers
{
    public class PhotoController : Controller
    {
        //
        // GET: /Photo/

        //public ActionResult Index()
        //{
        //    return View();
        //}

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
        public ActionResult Column(Entity story)
        {
            var photos = new PhotosByStoryQuery(story).Load(session);
            return View(Tuple.Create(photos, story));
        }

        [HttpPost]
        public void Remove(string storyType, int id, int photoId)
        {
            var Story = (Entity)session.Load(storyType, id);
            if (Story == null) throw new ArgumentException("Объект не найден");
            if (!((IPhotoContainer)Story).CanDelete(userSession.CurrentUser)) throw new UnauthorizedAccessException();

            var photo = session.Get<Photo>(photoId);
            yandexFotki.Delete(photo);
            session.Delete(photo);
            return;
        }

        [HttpGet]
        public ViewResult UploadPhotos(string storyType, int id, string returnUrl)
        {
            var Story = (Entity)session.Load(storyType, id); //var project = session.Get<Project>(id);
            if (Story == null) throw new ArgumentException("Объект не найден");
            if (!((IPhotoContainer)Story).CanUpload(userSession.CurrentUser)) throw new UnauthorizedAccessException();
            ViewBag.StoryId = id;
            ViewBag.StoryType = storyType;
            ViewBag.returnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        public JsonResult Upload(string storyType, int id, HttpPostedFileBase photo)
        {
            var filename = "";
            var photoUrl = "";
            try
            {
                if (photo == null) throw new ArgumentException("Файл не загружен");

                filename = photo.FileName;
                var Story = (Entity)session.Load(storyType, id); //var project = session.Get<Project>(id);
                if (Story == null) throw new ArgumentException("Объект не найден");
                if (!((IPhotoContainer)Story).CanUpload(userSession.CurrentUser)) throw new UnauthorizedAccessException();
                var albumUrl = yandexFotki.GetOrCreateAlbum(((IPhotoContainer)Story).AlbumName);

                var img = new Bitmap(photo.InputStream);
                Photo newPhoto = yandexFotki.UploadPhoto(img, albumUrl);
                newPhoto.Story = Story;
                session.Save(newPhoto);//project.Photos.Add(newPhoto);
                photoUrl = newPhoto.XlSizeUrl;
                return Json(new { code = 200, photoUrl = photoUrl, filename = filename, message = "Фотография сохранена" });
            }
            catch (ArgumentException ex)
            {
                return Json(new { code = 500, photoUrl = photoUrl, filename = filename, message = ex.Message });
            }
            catch (UnauthorizedAccessException ex)
            {
                return Json(new { code = 403, photoUrl = photoUrl, filename = filename, message = ex.Message });
            }
            catch
            {
                return Json(new { code = 500, photoUrl = photoUrl, filename = filename, message = "Загрузка фотографий временно не работает. Попробуйте позже." });
            }
        }

        public PhotoController(ISession session, IUserSession userSession, IAuthorizationService authz, YandexFotki yandexFotki)
        {
            this.session = session;
            this.userSession = userSession;
            this.authz = authz;
            this.yandexFotki = yandexFotki;
        }

        private readonly ISession session;
        private readonly IUserSession userSession;
        readonly IAuthorizationService authz;
        readonly YandexFotki yandexFotki;
    }
}
